// content.js - 视频录制助手
// 检测页面视频、截图和录制功能

// 检查是否已经初始化，避免重复声明
if (window.video_recording_assistant_initialized) {
  console.log("视频录制助手已经初始化，跳过重复加载");
} else {
  window.video_recording_assistant_initialized = true;
  
  // 全局变量
  let video_elements_cache = [];
  let media_recorder = null;
  let recorded_chunks = [];
  let is_recording = false;
  let current_video_element = null;
  let recording_start_time = null;

// 检测页面中正在播放的视频
function detect_playing_videos(force_update = false) {
  // 检查URL是否发生变化，如果变化则强制更新
  const current_url = window.location.href;
  if (window.last_detection_url !== current_url) {
    force_update = true;
    window.last_detection_url = current_url;
    video_elements_cache = []; // 清空缓存
  }
  
  if (!force_update && video_elements_cache.length > 0) {
    return Promise.resolve(video_elements_cache);
  }

  // 检测所有video元素
  const video_elements = document.querySelectorAll('video');
  
  // 收集所有视频信息
  const video_promises = [];
  
  video_elements.forEach((video, index) => {
    // 跳过隐藏的视频元素
    if (video.style.display === 'none' || video.style.visibility === 'hidden' || video.hidden) {
      return;
    }
    
    // 跳过尺寸为0的视频元素
    if (video.offsetWidth === 0 || video.offsetHeight === 0) {
      return;
    }
    
    // 跳过没有src且没有source标签的视频元素
    if (!video.src && !video.currentSrc && video.querySelectorAll('source').length === 0) {
      return;
    }
    
    // 创建视频信息收集Promise
    const video_promise = collect_video_info(video, index);
    video_promises.push(video_promise);
  });
  
  // 等待所有视频信息收集完成
  return Promise.all(video_promises).then(results => {
    const all_videos = results.filter(result => result !== null);
    
    // 去重：基于视频元素去重
    const unique_videos = [];
    const seen_elements = new Set();
    
    all_videos.forEach(video => {
      if (!seen_elements.has(video.element)) {
        seen_elements.add(video.element);
        unique_videos.push(video);
      }
    });
    
    // 如果检测到多个视频，根据时长进行过滤
    if (unique_videos.length > 1) {
      const filtered_videos = filter_videos_by_duration(unique_videos);
      video_elements_cache = filtered_videos;
      return filtered_videos;
    }
    
    video_elements_cache = unique_videos;
    return unique_videos;
  });
}

// 收集单个视频的信息，等待视频加载完成
function collect_video_info(video, index) {
  return new Promise((resolve) => {
    // 如果视频已经加载完成且有时长信息
    if (video.readyState >= 2 && video.duration && !isNaN(video.duration) && video.duration > 0) {
      const video_info = create_video_info(video, index);
      resolve(video_info);
      return;
    }
    
    // 如果视频还没有加载完成，等待加载
    const timeout = setTimeout(() => {
      const video_info = create_video_info(video, index);
      resolve(video_info);
    }, 3000); // 3秒超时
    
    // 监听视频加载事件
    const onLoadedMetadata = () => {
      clearTimeout(timeout);
      const video_info = create_video_info(video, index);
      resolve(video_info);
    };
    
    const onCanPlay = () => {
      clearTimeout(timeout);
      const video_info = create_video_info(video, index);
      resolve(video_info);
    };
    
    const onError = () => {
      clearTimeout(timeout);
      const video_info = create_video_info(video, index);
      resolve(video_info);
    };
    
    video.addEventListener('loadedmetadata', onLoadedMetadata, { once: true });
    video.addEventListener('canplay', onCanPlay, { once: true });
    video.addEventListener('error', onError, { once: true });
    
    // 如果视频还没有开始加载，尝试触发加载
    if (video.readyState === 0) {
      video.load();
    }
  });
}

// 创建视频信息对象
function create_video_info(video, index) {
  // 获取视频的当前状态
  const isPlaying = !video.paused;
  const isLoaded = video.readyState >= 2;
  const duration = video.duration || 0;
  const currentTime = video.currentTime || 0;
  
  // 优先检测video元素的src属性
  if (video.src || video.currentSrc) {
    return {
      url: video.src || video.currentSrc,
      title: get_video_title(video, index),
      element: video,
      isPlaying: isPlaying,
      isLoaded: isLoaded,
      duration: duration,
      currentTime: currentTime,
      index: index,
      // 添加更多状态信息用于调试
      readyState: video.readyState,
      networkState: video.networkState,
      paused: video.paused,
      ended: video.ended,
      muted: video.muted,
      volume: video.volume
    };
  } 
  // 如果video没有src，则检测source标签
  else {
    const sources = video.querySelectorAll('source');
    if (sources.length > 0) {
      // 只使用第一个有效的source标签
      for (let source_index = 0; source_index < sources.length; source_index++) {
        const source = sources[source_index];
        if (source.src && source.type && source.type.includes('video')) {
          return {
            url: source.src,
            title: get_video_title(video, index),
            element: video,
            isPlaying: isPlaying,
            isLoaded: isLoaded,
            duration: duration,
            currentTime: currentTime,
            index: index,
            // 添加更多状态信息用于调试
            readyState: video.readyState,
            networkState: video.networkState,
            paused: video.paused,
            ended: video.ended,
            muted: video.muted,
            volume: video.volume
          };
        }
      }
    }
  }
  
  return null;
}

// 根据视频状态和时长过滤视频，优先选择正在播放的视频
function filter_videos_by_duration(videos) {
  if (videos.length <= 1) {
    return videos;
  }
  
  // 过滤掉无效时长的视频
  const valid_videos = videos.filter(video => {
    const duration = video.duration;
    return duration && !isNaN(duration) && duration > 0 && duration < 86400; // 小于24小时
  });
  
  if (valid_videos.length === 0) {
    return [videos[0]];
  }
  
  if (valid_videos.length === 1) {
    console.log("只有一个有效时长的视频");
    return valid_videos;
  }
  
  // 优先选择正在播放的视频
  const playing_videos = valid_videos.filter(video => !video.element.paused);
  
  if (playing_videos.length > 0) {
    // 如果有正在播放的视频，选择播放时间最长的那个
    playing_videos.sort((a, b) => b.element.currentTime - a.element.currentTime);
    const selected_video = playing_videos[0];
    console.log("选择正在播放的视频:", selected_video.title, "播放时间:", selected_video.element.currentTime.toFixed(2));
    return [selected_video];
  }
  
  // 如果没有正在播放的视频，选择最近播放过的视频（currentTime > 0）
  const recently_played = valid_videos.filter(video => video.element.currentTime > 0);
  if (recently_played.length > 0) {
    recently_played.sort((a, b) => b.element.currentTime - a.element.currentTime);
    const selected_video = recently_played[0];
    console.log("选择最近播放的视频:", selected_video.title, "播放时间:", selected_video.element.currentTime.toFixed(2));
    return [selected_video];
  }
  
  // 如果都没有播放记录，选择时长最长的视频
  valid_videos.sort((a, b) => b.duration - a.duration);
  
  const selected_video = valid_videos[0];
  
  return [selected_video];
}

// 格式化时长显示
function format_duration(seconds) {
  if (!seconds || isNaN(seconds)) return '未知';
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);
  
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  } else {
    return `${minutes}:${secs.toString().padStart(2, '0')}`;
  }
}

// 获取视频标题
function get_video_title(video, index) {
  // 尝试从视频元素获取标题
  if (video.title) return video.title;
  
  // 尝试从父元素获取标题
  const parent = video.parentElement;
  if (parent && parent.textContent) {
    const text = parent.textContent.trim();
    if (text.length > 0 && text.length < 100) {
      return text;
    }
  }
  
  // 使用文档标题
  if (document.title) {
    return document.title + '_video_' + (index + 1);
  }
  
  return `Video_${index + 1}`;
}

// 规范化URL
function normalize_url(url) {
  try {
    return new URL(url, window.location.href).href;
  } catch {
    return url;
  }
}

// 开始录制
function start_recording(video_index = 0) {
  return new Promise((resolve, reject) => {
    if (is_recording) {
      reject(new Error("录制已在进行中"));
      return;
    }

    // 使用缓存的视频信息
    const videos = video_elements_cache;
    if (videos.length === 0) {
      reject(new Error("未找到可录制的视频"));
      return;
    }

    // 根据索引选择视频元素
    if (video_index >= videos.length) {
      reject(new Error(`视频索引 ${video_index} 超出范围，共有 ${videos.length} 个视频`));
      return;
    }

    const video_element = videos[video_index].element;
    current_video_element = video_element;
    
    try {
      // 检查视频元素是否有效
      if (!video_element || video_element.readyState < 1) {
        throw new Error("视频元素无效或未加载");
      }
      
      // 确保视频开始播放
      if (video_element.paused) {
        video_element.play().catch(error => {
          console.warn("自动播放失败，可能需要用户交互:", error);
        });
      }
      
      // 检查视频是否有有效的源
      if (!video_element.src && !video_element.currentSrc && video_element.querySelectorAll('source').length === 0) {
        throw new Error("视频没有有效的源");
      }
      
      // 检查视频是否已加载
      if (video_element.readyState < 2) {
        video_element.addEventListener('canplay', function onCanPlay() {
          video_element.removeEventListener('canplay', onCanPlay);
          startMediaRecorder();
        }, { once: true });
        return;
      } else {
        startMediaRecorder();
      }
      
      function startMediaRecorder() {
        try {
          // 创建视频流
          const stream = video_element.captureStream();
          
          // 检查流是否有效
          if (!stream || stream.getTracks().length === 0) {
            throw new Error("无法捕获视频流，请确保视频正在播放");
          }
          
          // 检查支持的MIME类型，按优先级排序
          const supportedTypes = [
            'video/webm;codecs=vp9',
            'video/webm;codecs=vp8', 
            'video/webm',
            'video/mp4;codecs=h264',
            'video/mp4',
            'video/ogg;codecs=theora'
          ];
          
          let selectedType = null;
          for (const type of supportedTypes) {
            if (MediaRecorder.isTypeSupported(type)) {
              selectedType = type;
              break;
            }
          }
          
          if (!selectedType) {
            try {
              media_recorder = new MediaRecorder(stream);
            } catch (error) {
              console.error("创建默认MediaRecorder失败:", error);
              throw new Error("浏览器不支持视频录制功能");
            }
          } else {
            try {
              media_recorder = new MediaRecorder(stream, {
                mimeType: selectedType
              });
            } catch (error) {
              console.error("创建指定MIME类型的MediaRecorder失败:", error);
              // 尝试使用默认设置
              media_recorder = new MediaRecorder(stream);
            }
          }
          
          recorded_chunks = [];
          
          media_recorder.ondataavailable = function(event) {
            if (event.data.size > 0) {
              recorded_chunks.push(event.data);
            }
          };
          
          media_recorder.onstop = function() {
            // 录制完成
          };
          
          media_recorder.onerror = function(event) {
            console.error("MediaRecorder错误:", event.error);
          };
          
          media_recorder.onstart = function() {
            // 录制开始
          };
          
          // 开始录制，每1000ms收集一次数据（增加间隔确保数据完整性）
          media_recorder.start(1000);
          is_recording = true;
          recording_start_time = Date.now();
          
          resolve({success: true});
          
        } catch (error) {
          console.error("创建MediaRecorder失败:", error);
          reject(error);
        }
      }
      
    } catch (error) {
      console.error("开始录制失败:", error);
      reject(error);
    }
  });
}

// 停止录制
function stop_recording() {
  return new Promise((resolve, reject) => {
    if (!is_recording || !media_recorder) {
      reject(new Error("没有正在进行的录制"));
      return;
    }

    try {
      console.log("开始停止录制，当前数据块数量:", recorded_chunks.length);
      
      // 检查录制时间是否足够
      const recordingDuration = Date.now() - (recording_start_time || Date.now());
      if (recordingDuration < 1000) {
        console.warn("录制时间太短，可能影响文件完整性");
      }
      
      // 停止MediaRecorder
      if (media_recorder.state === 'recording') {
        media_recorder.stop();
        console.log("MediaRecorder已停止");
      }
      
      is_recording = false;
      
      // 停止视频播放
      if (current_video_element && !current_video_element.paused) {
        console.log("停止视频播放");
        current_video_element.pause();
      }
      
      // 等待数据收集完成，使用更长的等待时间
      setTimeout(() => {
        if (recorded_chunks.length > 0) {
          // 根据MediaRecorder的MIME类型确定blob类型
          let blobType = 'video/webm';
          if (media_recorder.mimeType) {
            blobType = media_recorder.mimeType;
          }
          
          // 确保blob类型正确
          if (blobType.includes('webm')) {
            blobType = 'video/webm';
          } else if (blobType.includes('mp4')) {
            blobType = 'video/mp4';
          } else if (blobType.includes('ogg')) {
            blobType = 'video/ogg';
          }
          
          const blob = new Blob(recorded_chunks, {type: blobType});
          
          console.log("录制完成，文件大小:", blob.size, "字节，类型:", blobType);
          
          // 检查文件大小是否合理
          if (blob.size < 1024) {
            console.warn("录制的文件太小，可能存在问题");
          }
          
          // 创建下载URL
          const download_url = URL.createObjectURL(blob);
          console.log("创建的下载URL:", download_url);
          
          // 将blob数据转换为base64，以便在消息中传递
          const reader = new FileReader();
          reader.onload = function() {
            const base64Data = reader.result;
            console.log("Blob转换为base64完成，数据长度:", base64Data.length);
            
            // 清理录制状态
            recorded_chunks = [];
            media_recorder = null;
            current_video_element = null;
            recording_start_time = null;
            
            // 返回成功结果，包含base64数据
            const result = {
              success: true,
              downloadUrl: download_url,
              base64Data: base64Data,
              fileSize: blob.size,
              mimeType: blobType
            };
            
            resolve(result);
          };
          
          reader.onerror = function() {
            console.error("转换blob为base64失败");
            reject(new Error("转换录制数据失败"));
          };
          
          reader.readAsDataURL(blob);
          
        } else {
          console.error("录制数据为空，可能的原因：");
          console.error("- 录制时间太短");
          console.error("- 视频流捕获失败");
          console.error("- MediaRecorder配置问题");
          
          // 清理录制状态
          recorded_chunks = [];
          media_recorder = null;
          current_video_element = null;
          recording_start_time = null;
          
          reject(new Error("录制数据为空，请确保录制时间足够长且视频正在播放"));
        }
      }, 3000); // 增加到3秒等待时间
      
    } catch (error) {
      console.error("停止录制失败:", error);
      
      // 清理录制状态
      recorded_chunks = [];
      media_recorder = null;
      current_video_element = null;
      recording_start_time = null;
      is_recording = false;
      
      reject(error);
    }
  });
}

// 截图功能
function take_screenshot(video_index = 0) {
  return new Promise((resolve, reject) => {
    // 使用缓存的视频信息
    const videos = video_elements_cache;
    if (videos.length === 0) {
      reject(new Error("未找到可截图的视频"));
      return;
    }

    // 根据索引选择视频元素
    if (video_index >= videos.length) {
      reject(new Error(`视频索引 ${video_index} 超出范围，共有 ${videos.length} 个视频`));
      return;
    }

    // 选择指定索引的视频元素进行截图
    const video_element = videos[video_index].element;
    
    try {
      // 创建canvas捕获当前帧
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      
      // 设置canvas尺寸
      canvas.width = video_element.videoWidth || 640;
      canvas.height = video_element.videoHeight || 480;
      
      // 绘制视频帧到canvas
      ctx.drawImage(video_element, 0, 0, canvas.width, canvas.height);
      
      // 转换为blob并创建下载链接
      canvas.toBlob((blob) => {
        if (blob) {
          const download_url = URL.createObjectURL(blob);
          console.log(`截图生成完成，视频索引: ${video_index}，文件大小:`, blob.size);
          
          // 将blob数据转换为base64
          const reader = new FileReader();
          reader.onload = function() {
            const base64Data = reader.result;
            console.log("截图base64数据长度:", base64Data.length);
            
            resolve({
              success: true,
              downloadUrl: download_url,
              base64Data: base64Data,
              fileSize: blob.size
            });
          };
          
          reader.onerror = function() {
            console.error("转换截图blob为base64失败");
            reject(new Error("转换截图数据失败"));
          };
          
          reader.readAsDataURL(blob);
        } else {
          reject(new Error("无法生成截图"));
        }
      }, 'image/png');
      
    } catch (error) {
      console.error("截图失败:", error);
      reject(error);
    }
  });
}

// 监听来自 popup 的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === "getVideos") {
    // 强制重新检测视频，不使用缓存
    detect_playing_videos(true)
      .then(videos => {
        // 更新视频的实时状态
        const updated_videos = videos.map(video => {
          const element = video.element;
          return {
            ...video,
            isPlaying: !element.paused,
            currentTime: element.currentTime || 0,
            duration: element.duration || 0,
            readyState: element.readyState,
            networkState: element.networkState,
            paused: element.paused,
            ended: element.ended,
            muted: element.muted,
            volume: element.volume
          };
        });
        
        sendResponse({videos: updated_videos});
      })
      .catch(error => {
        console.error("检测视频时出错:", error);
        sendResponse({videos: [], error: error.message});
      });
    return true;
  }
  else if (request.action === "startRecording") {
    detect_playing_videos()
      .then(videos => {
        if (videos.length === 0) {
          sendResponse({success: false, error: "未找到可录制的视频"});
          return;
        }
        return start_recording(request.videoIndex || 0);
      })
      .then(result => {
        if (result) {
          sendResponse(result);
        }
      })
      .catch(error => {
        console.error("开始录制失败:", error);
        sendResponse({success: false, error: error.message});
      });
    return true;
  }
  else if (request.action === "stopRecording") {
    stop_recording()
      .then(result => {
        sendResponse(result);
      })
      .catch(error => {
        console.error("停止录制失败:", error);
        sendResponse({success: false, error: error.message});
      });
    return true;
  }
  else if (request.action === "takeScreenshot") {
    detect_playing_videos()
      .then(videos => {
        if (videos.length === 0) {
          sendResponse({success: false, error: "未找到可截图的视频"});
          return;
        }
        return take_screenshot(request.videoIndex || 0);
      })
      .then(result => {
        if (result) {
          sendResponse(result);
        }
      })
      .catch(error => {
        console.error("截图失败:", error);
        sendResponse({success: false, error: error.message});
      });
    return true;
  }
  
  return true;
});

// 页面加载完成后检测视频
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => {
      detect_playing_videos(false).catch(error => {
        console.error("页面加载完成后检测视频失败:", error);
      });
    }, 1000);
  });
} else {
  setTimeout(() => {
    detect_playing_videos(false).catch(error => {
      console.error("页面已加载时检测视频失败:", error);
    });
  }, 1000);
}

// 监听页面变化，更新视频元素缓存
const observer = new MutationObserver(function(mutations) {
  let should_update = false;
  let url_changed = false;
  
  mutations.forEach(function(mutation) {
    // 检查URL变化
    if (mutation.type === 'attributes' && mutation.target === document.querySelector('base')) {
      url_changed = true;
      should_update = true;
    }
    
    if (mutation.type === 'childList') {
      mutation.addedNodes.forEach(function(node) {
        if (node.nodeType === 1) {
          // 检查是否有video元素
          if (node.tagName === 'VIDEO' || node.querySelector('video')) {
            should_update = true;
          }
          // 检查是否有iframe（可能包含视频）
          if (node.tagName === 'IFRAME' || node.querySelector('iframe')) {
            should_update = true;
          }
          // 检查是否有动态加载的内容
          if (node.classList && (node.classList.contains('video') || node.classList.contains('player'))) {
            should_update = true;
          }
          // 检查是否有视频相关的容器
          if (node.id && (node.id.includes('video') || node.id.includes('player') || node.id.includes('media'))) {
            should_update = true;
          }
        }
      });
      
      // 检查移除的节点
      mutation.removedNodes.forEach(function(node) {
        if (node.nodeType === 1 && (node.tagName === 'VIDEO' || node.querySelector('video'))) {
          should_update = true;
        }
      });
    }
    
    // 监听属性变化（如src、style等）
    if (mutation.type === 'attributes') {
      const target = mutation.target;
      if (target.tagName === 'VIDEO' || target.closest('video')) {
        should_update = true;
      }
      // 检查视频相关元素的属性变化
      if (target.id && (target.id.includes('video') || target.id.includes('player'))) {
        should_update = true;
      }
    }
  });
  
  if (should_update) {
    // 使用防抖，避免频繁更新
    clearTimeout(window.video_detection_timeout);
    window.video_detection_timeout = setTimeout(() => {
      // 如果URL发生变化，强制重新检测
      if (url_changed) {
        detect_playing_videos(true).catch(error => {
          console.error("页面变化时检测视频失败:", error);
        });
      } else {
        detect_playing_videos(false).catch(error => {
          console.error("页面变化时检测视频失败:", error);
        });
      }
    }, 300);
  }
});

// 开始观察页面变化
observer.observe(document.body, {
  childList: true,
  subtree: true,
  attributes: true,
  attributeFilter: ['src', 'style', 'class', 'hidden']
});

// 监听iframe加载完成
function setup_iframe_listeners() {
  const iframes = document.querySelectorAll('iframe');
  iframes.forEach(iframe => {
    try {
      if (iframe.contentDocument) {
        setup_video_observer(iframe.contentDocument);
      }
    } catch (e) {
      // 跨域iframe无法访问
      console.log("无法访问iframe内容（可能是跨域限制）");
    }
  });
}

// 为iframe内的文档设置视频监听
function setup_video_observer(doc) {
  if (!doc || doc === document) return;
  
  const iframe_observer = new MutationObserver(function(mutations) {
    let should_update = false;
    mutations.forEach(function(mutation) {
      if (mutation.type === 'childList') {
        mutation.addedNodes.forEach(function(node) {
          if (node.nodeType === 1 && (node.tagName === 'VIDEO' || node.querySelector('video'))) {
            should_update = true;
          }
        });
      }
    });
    
    if (should_update) {
      setTimeout(() => {
        detect_playing_videos(false).catch(error => {
          console.error("iframe变化时检测视频失败:", error);
        });
      }, 500);
    }
  });
  
  iframe_observer.observe(doc.body, {
    childList: true,
    subtree: true
  });
}

// 监听新添加的iframe
const iframe_observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type === 'childList') {
      mutation.addedNodes.forEach(function(node) {
        if (node.nodeType === 1 && node.tagName === 'IFRAME') {
          node.addEventListener('load', function() {
            setup_video_observer(this.contentDocument);
          });
        }
      });
    }
  });
});

iframe_observer.observe(document.body, {
  childList: true,
  subtree: true
});

// 初始化iframe监听
setup_iframe_listeners();

// 监听URL变化（用于单页应用）
let current_url = window.location.href;
function check_url_change() {
  if (window.location.href !== current_url) {
    current_url = window.location.href;
    // 延迟重新检测，确保页面内容已更新
    setTimeout(() => {
      detect_playing_videos(true).catch(error => {
        console.error("URL变化时检测视频失败:", error);
      });
    }, 500);
  }
}

// 监听popstate事件（浏览器前进后退）
window.addEventListener('popstate', function() {
  setTimeout(() => {
    detect_playing_videos(true).catch(error => {
      console.error("popstate事件时检测视频失败:", error);
    });
  }, 300);
});

// 监听pushstate和replacestate事件
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;

history.pushState = function() {
  originalPushState.apply(this, arguments);
  setTimeout(() => {
    check_url_change();
  }, 100);
};

history.replaceState = function() {
  originalReplaceState.apply(this, arguments);
  setTimeout(() => {
    check_url_change();
  }, 100);
};

// 定期检查URL变化（备用方案）
setInterval(check_url_change, 1000);

} // 结束 if (window.video_recording_assistant_initialized) 的 else 块 